package com.fc.push.handler.pub;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.fc.commons.DateUtil;
import com.fc.persistence.cache.redis.SharedJedisFacade;
import com.fc.persistence.dao.DAOTemplate;
import com.fc.push.GlobalServerConst;
import com.fc.push.db.TranscationFacade;
import com.fc.push.db.entities.IMessage;
import com.fc.push.handler.AbstractHttpHandler;
import com.fc.push.handler.HandlerResult;
import com.fc.remoting.anno.Protocol;

@Component
@Protocol(module = PublishConst.PUBLISH_MODULE_ID, order = PublishConst.ORDER_2)
public class GetPublishMessageHandler extends AbstractHttpHandler{
private static final int CONST_COUNT = 50;
	
	private static final String APPKEY = "appkey";
	private static final String START_TIME = "starttime";
	private static final String END_TIME = "endtime";
	private static final String INDEX = "index";
	
	private static final String DATA = "data";
	private static final String TOTAL_COUNT = "total_count";
	
	private static final String CODE = "code";
	@Override
	public Object handle(HttpServletResponse response, JSONObject request) {
		String appkey = request.getString(APPKEY);
		long starttime = request.getLongValue(START_TIME);
		long endtime = request.getLongValue(END_TIME);
		int index = request.getIntValue(INDEX);
		
		String sql = "";
		List<DAOTemplate> res = null;
		JSONObject result = HandlerResult.result();
		if(starttime == 0 || endtime == 0){
			sql = "from " + IMessage.class.getSimpleName() + " where appkey='" + appkey  + "' order by createdate desc";
			res = TranscationFacade.getInstance().transcation().getBySQL(sql,index,CONST_COUNT);
			String countkey = GlobalServerConst.APP_MESSAGE_COUNT.replaceFirst("APP", appkey);
			String count = "0";
			if(SharedJedisFacade.existsProxy(countkey)){
				count = SharedJedisFacade.getProxy(countkey);
			}
			result.put(TOTAL_COUNT, Integer.parseInt(count));
		}else{
			Date sDate = new Date(starttime);
			Date eDate = new Date(endtime);
			String sFormate = DateUtil.formatDate(sDate, DateUtil.PATTERN_DATE_TIME);
			String eFormate = DateUtil.formatDate(eDate, DateUtil.PATTERN_DATE_TIME);
			if(starttime == 0){
				JSONObject object = HandlerResult.result();
				object.put(CODE, MessageRCode.RCODE_ERROR_1002);
				return object;
			}else if(endtime == 0){
				JSONObject object = HandlerResult.result();
				object.put(CODE, MessageRCode.RCODE_ERROR_1002);
				return object;
			}
			sql = "from " + IMessage.class.getSimpleName() + " where appkey='" + appkey  + "' and createdate between '" + sFormate + "' and '" + eFormate + "' order by createdate desc";
			res = TranscationFacade.getInstance().transcation().getBySQL(sql);
			
			result.put(TOTAL_COUNT, res.size());
		}
		if(res == null){
			res = new ArrayList<DAOTemplate>();
		}
		result.put(DATA, res);
		return result;
	}

}
